// Logo生成WebSocket连接示例
class LogoGenerationWebSocket {
    constructor(userId) {
        this.userId = userId;
        this.socket = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000; // 3秒重连间隔
        
        this.init();
    }
    
    init() {
        this.connect();
    }
    
    connect() {
        try {
            // 建立WebSocket连接
            this.socket = new WebSocket(`ws://localhost:8000/ws/logo-generation/${this.userId}/`);
            
            this.socket.onopen = (event) => {
                console.log('Logo生成WebSocket连接已建立');
                this.isConnected = true;
                this.reconnectAttempts = 0;
                
                // 发送连接确认消息
                this.sendMessage({
                    type: 'ping',
                    timestamp: Date.now()
                });
            };
            
            this.socket.onmessage = (event) => {
                this.handleMessage(event.data);
            };
            
            this.socket.onclose = (event) => {
                console.log('Logo生成WebSocket连接已关闭');
                this.isConnected = false;
                this.handleReconnect();
            };
            
            this.socket.onerror = (error) => {
                console.error('Logo生成WebSocket连接错误:', error);
                this.isConnected = false;
            };
            
        } catch (error) {
            console.error('建立WebSocket连接失败:', error);
            this.handleReconnect();
        }
    }
    
    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            console.log('收到WebSocket消息:', message);
            
            switch (message.type) {
                case 'connection_established':
                    console.log('WebSocket连接已确认');
                    break;
                    
                case 'pong':
                    console.log('收到心跳响应');
                    break;
                    
                case 'logo_progress':
                    this.handleLogoProgress(message.data);
                    break;
                    
                case 'logo_result':
                    this.handleLogoResult(message.data);
                    break;
                    
                case 'error':
                    console.error('WebSocket错误:', message.message);
                    break;
                    
                default:
                    console.log('未知消息类型:', message.type);
            }
        } catch (error) {
            console.error('解析WebSocket消息失败:', error);
        }
    }
    
    handleLogoProgress(data) {
        console.log('Logo生成进度:', data);
        
        // 更新UI显示进度
        const { status, message, progress } = data;
        
        // 示例：更新进度条
        if (window.updateLogoProgress) {
            window.updateLogoProgress(progress, message);
        }
        
        // 示例：显示状态消息
        if (window.showLogoStatus) {
            window.showLogoStatus(status, message);
        }
    }
    
    handleLogoResult(data) {
        console.log('Logo生成结果:', data);
        
        if (data.success) {
            console.log('Logo生成成功:', data.image_url);
            
            // 示例：显示成功消息
            if (window.showLogoSuccess) {
                window.showLogoSuccess(data.image_url, data.message);
            }
            
            // 示例：更新用户头像
            if (window.updateUserLogo) {
                window.updateUserLogo(data.image_url);
            }
        } else {
            console.error('Logo生成失败:', data.message);
            
            // 示例：显示错误消息
            if (window.showLogoError) {
                window.showLogoError(data.message);
            }
        }
    }
    
    sendMessage(message) {
        if (this.isConnected && this.socket) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.warn('WebSocket未连接，无法发送消息');
        }
    }
    
    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            
            setTimeout(() => {
                this.connect();
            }, this.reconnectInterval);
        } else {
            console.error('WebSocket重连失败，已达到最大重试次数');
        }
    }
    
    disconnect() {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
            this.isConnected = false;
        }
    }
    
    // 发送心跳检测
    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.isConnected) {
                this.sendMessage({
                    type: 'ping',
                    timestamp: Date.now()
                });
            }
        }, 30000); // 每30秒发送一次心跳
    }
    
    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }
}

// 使用示例
// const logoWebSocket = new LogoGenerationWebSocket(userId);
// logoWebSocket.startHeartbeat();

// 页面卸载时清理
// window.addEventListener('beforeunload', () => {
//     if (logoWebSocket) {
//         logoWebSocket.stopHeartbeat();
//         logoWebSocket.disconnect();
//     }
// });
